package com.cetccst.securitysuite.fragments;

import static android.content.Context.WINDOW_SERVICE;

import android.content.Intent;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;

import com.cetccst.securitysuite.BR;
import com.cetccst.securitysuite.R;
import com.cetccst.securitysuite.databinding.FragmentLoginBinding;
import com.cetccst.securitysuite.fragments.viewmodel.LoginViewModel;
import com.cetccst.securitysuite.uicomponents.watermark.WaterMarkTextView;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import cn.com.cetccst.appstore.ui.activity.AppStoreActivity;
import cn.com.cetccst.basiccollection.BasicInfoEngine;
import cn.com.cetccst.datacenter.collection.entity.CollectionConfigEntity;
import cn.com.cetccst.datacenter.collection.entity.LocationRecordEntity;
import cn.com.cetccst.datacenter.message.InboxMessageRespository;
import cn.com.cetccst.datacenter.message.entity.InboxMessageEntity;
import cn.com.cetccst.datacenter.collection.entity.LocationRecordEntity;
import cn.com.cetccst.datacenter.policy.PolicyRepository;
import cn.com.cetccst.datacenter.policy.entity.RestrictionEntity;
import cn.com.cetccst.hostsdk.internal.SDKErrorCode;
import cn.com.cetccst.hostsdk.internal.SSApiImplLocal;
import cn.com.cetccst.location.LocationService;
import cn.com.cetccst.messagecenter.inboxmessage.InboxMessageActivity;
import cn.com.cetccst.sdk.modelbiz.ReceivePayloadMessage;
import cn.com.cetccst.uicomponents.binding.app.DataBindingConfig;
import cn.com.cetccst.usercenter.ui.EditUserInfoActivity;
import cn.com.cetccst.usercenter.ui.UserInfoActivity;

public class LoginFragment extends BaseFragment<FragmentLoginBinding> {

    private LoginViewModel loginViewModel;

    private final ActivityResultLauncher<Intent> overlayLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
            result -> {
                if (Settings.canDrawOverlays(getContext())) {
                    popupGlobalWatermark();
                }
            });

    @Override
    protected void initViewModel() {
        loginViewModel = getFragmentScopeViewModel(LoginViewModel.class);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        LocationService.getInstance().getLocationRecordLiveData().observe(getViewLifecycleOwner(), new Observer<LocationRecordEntity>() {
            @Override
            public void onChanged(LocationRecordEntity locationRecordEntity) {
                Log.e("LocationService", "observer location changed : " + locationRecordEntity.toJson().toString());
            }
        });
    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        return new DataBindingConfig(R.layout.fragment_login, BR.viewModel, loginViewModel)
                .addBindingParam(BR.click, new Click());
    }

    public class Click {
        public void login() {
            loginViewModel.login(result -> {
//                if (result) {
                NavController navController = Navigation.findNavController(getView());
                navController.navigate(R.id.action_loginFragment_to_mainFragment, null);
//                } else {
//                    Toast.makeText(getContext(), "登录失败了", Toast.LENGTH_SHORT).show();
//                }
            });
        }

        public void secondActivity() {
            Intent intent = new Intent(getContext(), AppStoreActivity.class);
            startActivity(intent);
        }

        public void sendPayload() {
            //模拟透传
            SSApiImplLocal api = SSApiImplLocal.getInstance(null);

            ReceivePayloadMessage.Req req = new ReceivePayloadMessage.Req();
            req.message = "这是一条透传消息";
            req.time = System.currentTimeMillis();
            //TODO 透传消息需要知道第三方app的包名，推送协议可以获取
            api.sendReq("com.example.opensdkdemo", req, resp -> {
                if (resp.errorCode == SDKErrorCode.ERROR_OK) {
                    Toast.makeText(getContext(), "透传消息送达！", Toast.LENGTH_SHORT).show();
                }
            });
        }

        public void enterMqtt() {
            NavController navController = Navigation.findNavController(getView());
            navController.navigate(R.id.action_loginFragment_to_mqttFragment, null);
        }

        public void addmsg() {
            InboxMessageEntity entity = new InboxMessageEntity();
            entity.setTitle("测试标题-" + UUID.randomUUID().toString().substring(0, 4));
            entity.setReceivedDate(System.currentTimeMillis());
            entity.setSubject("测试主题-" + UUID.randomUUID().toString().substring(0, 4));
            entity.setContent("测试内容-" + UUID.randomUUID().toString());
            InboxMessageRespository.getInstance().saveMessage(entity);

            RestrictionEntity restrictionEntity = new RestrictionEntity();
            restrictionEntity.setName("camera");
            restrictionEntity.setValue(1);

            List<RestrictionEntity> entities = new ArrayList<>();
            entities.add(restrictionEntity);
            PolicyRepository.getInstance().saveAllRestriction(entities);

        }

        public void messageActivity() {
            Intent intent = new Intent(getContext(), InboxMessageActivity.class);
            startActivity(intent);
        }

        public void location() {
            LocationService.getInstance().start();
        }

        public void addFence() {
            double lat = 39.080763;
            double lon = 117.241535;
            LocationService.getInstance().getGeoFenceManager().createGlobalFence(lat, lon, 3);
        }

        public void compliance() {
            NavController navController = Navigation.findNavController(getView());
            navController.navigate(R.id.action_loginFragment_to_complianceFragment, null);
        }
        public void appshield() {
            NavController navController = Navigation.findNavController(getView());
            navController.navigate(R.id.action_loginFragment_to_appShieldFragment, null);
        }

        public void restrictions() {
            NavController navController = Navigation.findNavController(getView());
            navController.navigate(R.id.action_loginFragment_to_restrictionFragment, null);
        }

        public void watermark() {
            if (!Settings.canDrawOverlays(getContext())) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                        Uri.parse("package:" + getContext().getPackageName()));
                overlayLauncher.launch(intent);
                return;
            }
            popupGlobalWatermark();
        }

        public void peroidCollect() {
            CollectionConfigEntity config = new CollectionConfigEntity();
            config.setEnable("true");
            config.setHardware(15);
            config.setStatus(20);
            config.setApp(18);
            BasicInfoEngine.getInstance().peroidCollect(config);
        }

        public void editUserInfo() {
            Intent intent = new Intent(getContext(), EditUserInfoActivity.class);
            startActivity(intent);
        }

        public void showUserInfo() {
            Intent intent = new Intent(getContext(), UserInfoActivity.class);
            startActivity(intent);
        }
    }

    private void popupGlobalWatermark() {


        if (Boolean.FALSE.equals(loginViewModel.watermark.getValue())) {
            loginViewModel.watermark.setValue(true);

            //TODO 下面的代码可以放在viewmodel中，懒得弄了
            WindowManager windowManager = (WindowManager) getActivity().getSystemService(WINDOW_SERVICE);
            WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                    WindowManager.LayoutParams.MATCH_PARENT,
                    WindowManager.LayoutParams.MATCH_PARENT,
                    WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
                    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
//                            WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE |
//                            WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
                            WindowManager.LayoutParams.FIRST_SYSTEM_WINDOW,
                    PixelFormat.TRANSLUCENT);
            View view = LayoutInflater.from(getContext()).inflate(R.layout.system_alert_dialog, null);

            FrameLayout container = view.findViewById(R.id.container);
            final WaterMarkTextView waterMarkTextView = new WaterMarkTextView(getContext());

            waterMarkTextView.setWaterMarkText(new String[]{"测试， “15011111111"});
            waterMarkTextView.setShowTime(true);
            waterMarkTextView.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            waterMarkTextView.postInvalidate();

            container.addView(waterMarkTextView);
            windowManager.addView(view, params);
        }


    }

}